import 'package:flutter/material.dart';
import "package:jetour_line/utils/extension_int.dart";
import 'package:card_swiper/card_swiper.dart';

typedef SwiperBuilder = Function(BuildContext context, int index);

class CustomSwiper<T> extends StatelessWidget {
  final List<T> dataList;
  final SwiperBuilder swiperBuilder;
  final double height;
  final double betweenMargin;
  final double indicatorWidth;
  final Color indicatorColor;
  final Color checkedIndicatorColor;
  final Function? onTap;
  const CustomSwiper(
      {Key? key,
      required this.dataList,
      required this.swiperBuilder,
      required this.height,
      this.onTap,
      this.betweenMargin = 24,
      this.indicatorWidth = 6,
      this.indicatorColor = const Color(0x801a1a1a),
      this.checkedIndicatorColor = const Color(0xffffffff)})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ConstrainedBox(
      constraints: BoxConstraints.expand(height: height),
      child: Swiper(
        autoplay: true,
        index: 0,
        itemBuilder: (context, index) {
          if (dataList.isNotEmpty) {
            return Flex(direction: Axis.horizontal, children: [
              SizedBox(width: betweenMargin, height: height),
              Expanded(
                  flex: 1,
                  child: Builder(builder: (context) {
                    return swiperBuilder(context, index);
                  })),
              SizedBox(width: betweenMargin, height: height)
            ]);
          } else {
            return SizedBox(width: MediaQuery.of(context).size.width);
          }
        },
        onTap: (index) {
          if (onTap != null) {
            onTap!(dataList[index]);
          }
        },
        itemCount: dataList.isNotEmpty ? dataList.length : 1,
        pagination: SwiperPagination(
            margin: EdgeInsets.zero,
            builder: SwiperCustomPagination(builder: (context, config) {
              List<Widget> pagination = [];
              for (int i = 0; i < config.itemCount; i++) {
                bool checked = i == config.activeIndex;
                pagination.add(AnimatedContainer(
                  width: checked ? indicatorWidth * 4 : indicatorWidth,
                  height: indicatorWidth,
                  duration: const Duration(milliseconds: 300),
                  margin: EdgeInsets.all(10.rpx),
                  decoration: BoxDecoration(
                    color: checked ? checkedIndicatorColor : indicatorColor,
                    borderRadius: BorderRadius.all(
                      Radius.circular(indicatorWidth * 0.5),
                    ),
                  ),
                ));
              }
              return Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: pagination,
              );
            })),
      ),
    );
  }
}
